package com.application.module.withdraw;

import com.alibaba.fastjson.JSON;
import com.application.intercept.BaseInterceptor;
import com.application.model.Message;
import com.application.module.usermoney.WithdrawUserMoney;
import com.jfinal.aop.Invocation;
import com.jfinal.ext.kit.MsgException;
import com.jfinal.kit.StrKit;
import com.jfinal.render.JsonRender;
import com.platform.mvc.base.BaseController;
import com.platform.mvc.user.User;

import java.math.BigDecimal;
import java.util.Map;

public class WithdrawInterceptor extends BaseInterceptor {

    static String title = "提现申请消息";

    @Override
    protected void handler(Invocation invoc) {
        BaseController ct = (BaseController) invoc.getController();
        String jsonText = ((JsonRender) ct.getRender()).getJsonText();
        Map<String, Object> map = (Map<String, Object>) JSON.parse(jsonText);
        if ("200".equals(map.get("status").toString())) {
            Withdraw obj = Withdraw.dao.findById(ct.getPara("id"));
            switch (ct.getParaToInt("status")) {
                case Withdraw.STATUS_OK:
                    handlerOk(ct, obj);
                    break;
                case Withdraw.STATUS_REJECT:
                    handlerReject(obj);
                    break;
            }
        }
    }

    private void handlerReject(Withdraw obj) {
        String s = StrKit.notBlank(obj.getReply_content()) ? obj.getReply_content() : "您的申请已拒绝";
        sendMessage(obj, s);
    }

    private void sendMessage(Withdraw obj, String content) {
        if(StrKit.notBlank(content)) {
            Message.dao.createNotice(Message.MODULE_Withdraw, title, content, 0, obj.getApply_userid(),
                    "applyId:" + obj.getId());
        }
    }

    private void handlerOk(BaseController ct, Withdraw obj) {
        new WithdrawUserMoney().create(obj.getApply_userid(), "-" + obj.getApply_money().toString(), obj.getId().toString(), obj.getApply_userid());
        User user = User.dao.findById(obj.getApply_userid());
        BigDecimal money = user.getBigDecimal("money").subtract(obj.getApply_money());
        if (money.intValue() < 0) {//负数
            BigDecimal giftRemain = user.getBigDecimal("gift").add(money);
            if (giftRemain.intValue() < 0) {
                throw new MsgException("提取金额超过用户余额");
            } else {
                user.set("money", 0).set("gift", giftRemain).update();
            }
        } else {
            user.set("money", money).update();
        }

        String s = StrKit.notBlank(obj.getReply_content()) ? obj.getReply_content() : "您的申请已同意";
        sendMessage(obj, s);
//        WithdrawService.transferMoney(obj.getApply_no(), money, user.get("openid"));
    }

}
